<template>
  <div id="app">
    <el-container>
      <el-header></el-header>
      <el-main>
        <el-form :inline="true" :model="studentSearch" class="demo-form-inline" size="medium">
          <el-form-item label="学生姓名">
            <el-input v-model="studentSearch.sname" ></el-input>
          </el-form-item>
          <el-form-item label="学生住址">
            <el-input v-model="studentSearch.addr" ></el-input>
          </el-form-item>
          <el-form-item label="学生班级">
            <el-select v-model="studentSearch.cid" placeholder="所在班级">
              <el-option label="所有班级" value="0"></el-option>
              <el-option :label="c.cname" :value="c.cid" v-for="c in classesList" :key="c.cid"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="search" icon="el-icon-search" >查询</el-button>
            <el-button type="success" @click="addStudent" icon="el-icon-plus">添加</el-button>
            <el-button type="danger" @click="handleDelete" icon="el-icon-remove">批量删除</el-button>
          </el-form-item>
        </el-form>

        <el-card shadow="always">
          <el-table
              :data="studentList"
              style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column
                type="selection"
                width="55">
            </el-table-column>
            <el-table-column
                prop="sid"
                label="学号"
                align="center"
                width="180">
            </el-table-column>
            <el-table-column
                prop="sname"
                label="姓名"
                align="center"
                width="180">
            </el-table-column>
            <el-table-column
                prop="sex"
                label="性别"
                align="center"
                width="180">
            </el-table-column>
            <el-table-column
                prop="age"
                label="年龄"
                align="center"
                width="180">
            </el-table-column>
            <el-table-column
                prop="addr"
                align="center"
                width="180"
                label="地址">
            </el-table-column>
            <el-table-column
                prop="cname"
                label="班级"
                align="center"
                width="180">
            </el-table-column>

            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                    size="mini"
                    @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
<!--          分页导航-->
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page"
              :page-sizes="[5, 10, 15, 20]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
          </el-pagination>
        </el-card>

        <el-dialog :title="title" :visible.sync="dialogFormVisible">
          {{studentAdd}}
          <el-form :model="studentAdd" :rules="rules" ref="ruleForm">
            <el-form-item label="姓名" :label-width="formLabelWidth" prop="sname">
              <el-input v-model="studentAdd.sname" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="性别" :label-width="formLabelWidth" prop="sex">
                <el-radio-group v-model="studentAdd.sex">
                  <el-radio label="男"></el-radio>
                  <el-radio label="女"></el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="年龄" :label-width="formLabelWidth" prop="age">
              <el-input v-model.number="studentAdd.age" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="地址" :label-width="formLabelWidth" prop="addr">
              <el-input v-model="studentAdd.addr" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="班级" prop="cid" :label-width="formLabelWidth">
              <el-select v-model="studentAdd.cid" placeholder="所在班级">
                <el-option label="所有班级" value="0"></el-option>
                <el-option :label="c.cname" :value="c.cid" v-for="c in classesList" :key="c.cid"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveStudent">保 存</el-button>
          </div>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import studentApi from "@/api/student";
import classesApi from "@/api/classes";
export default {
  data() {
    var checkAge = (rule, value, callback) => {
      if (value === '' || value === null) {
        return callback(new Error('年龄不能为空'));
      }else if(!Number.isInteger(value)){
        callback(new Error('请输入数字值'));
      }else if ((value<1 || value>100)){
        callback(new Error('年龄范围1-100'));
      }else {
        callback();
      }
    };
    return {
      studentList: [],
      page: 1,//current page
      pageSize: 10,// Displays the number of records per page
      total: 100,// Total number of records
      studentSearch: {},
      classesList: [],
      title: "",
      dialogFormVisible: false,
      studentAdd:{},
      formLabelWidth: '120px',
      multipleSelection: [],
      sids: [],
      rules:{
        sname: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        age: [
          // { required: true, message: '请输入年龄', trigger: 'blur' },
          { validator: checkAge, trigger: 'blur'}
        ],
        addr: [
          { required: true, message: '请输入地址', trigger: 'blur' }
        ],
        cid: [
          { required: true, message: '请选择班级', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    // this.findByPage()
    this.search()
    this.findAllClasses()
  },
  methods:{
    async findSudents(){
      const {data:res} = await studentApi.findAllStudents()
      console.log(res.data.list)
      if (res.code === 200){
        this.studentList = res.data.list
      }
    },

    async findByPage(){
      const {data:res} = await studentApi.findByPage(this.page,this.pageSize)
      // console.log(res)
      if (res.code === 200){
        this.studentList = res.data.pr.rows
        this.total = res.data.pr.total
      }
    },
  async findAllClasses(){
      const {data:res} = await classesApi.findAllClasses()
      if (res.code === 200){
        this.classesList = res.data.list
      }
    },
    //条件查询带分页
    async search(){

      const {data:res} = await studentApi.search(this.page,this.pageSize,this.studentSearch)
      console.log(res)
      if (res.code === 200){
        this.studentList = res.data.pr.rows
        this.total = res.data.pr.total
      }
    },
    async addStudent(){
      this.title = "添加学生"
      // 清除缓存数据
      this.studentAdd= {}

      this.dialogFormVisible = true;
      // console.log(this.studentAdd)
      // const {data:res} = await studentApi.addStudent(this.studentAdd)
    },
    saveStudent(){
      this.$refs.ruleForm.validate(async valid => {
        let url = "/student/add"
        if(this.studentAdd.sid){
          url = "/student/update"
        }
        if(valid){
          console.log("success")
          const {data:res} = await studentApi.save(url,this.studentAdd)
          console.log(res)
          if (res.code === 200){
            this.$message({
              type: 'success',
              message: res.messages,
              onClose: () => {
                this.dialogFormVisible = false;
                this.search()
              }
            });
          }else{
            this.$message({
              type: 'error',
              message: res.messages
            });
          }
        }else{
          console.log("error submit!!");
          return false
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection)
    },

    handleEdit(index, row) {
      this.title = "修改学生"
      this.dialogFormVisible = true;
      console.log(index, row);
      this.studentAdd = row
    },
    handleDelete(index, row) {
      this.sids = []
      console.log(index, row);
      if(row){
        this.sids.push(row.sid)
      }else{
          this.sids = this.multipleSelection.map(item => item.sid)
      }
      this.$confirm(`是否真的要删除学号为${this.sids}的学生吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let _this = this
        studentApi.deleteById(this.sids).then(res => {
          console.log("res.data.message",res.data.message)
          if (res.data.code === 200){
            this.$message({
              type: 'success',
              message: res.data.messages,
              onClose: () => {
                _this.search()
              }
            });
          }else{
            this.$message({
              type: 'error',
              message: res.data.messages
            });
          }
        // this.$message({
        //   type: 'success',
        //   message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 每页大小改变时事件
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      // this.findByPage()
      this.search()
    },
    // 当前页改变时事件
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      // this.findByPage()
      this.search()
    },
  }
}


</script>

<style>
#app{
  display: flex;
  justify-content: center;

}

.el-card{
  width: 90%;
}

.el-pagination{
  margin-top: 20px;
  text-align: right;
}
</style>
